package com.sugon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.sugon.consts.ErmsCodePrefix;
import com.sugon.dao.DevMaintenanceTicketDao;
import com.sugon.dao.DevMaintenanceTicketItemDao;
import com.sugon.entity.DevMaintenanceTicketEntity;
import com.sugon.entity.DevMaintenanceTicketItemEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.modules.device.consts.DevMaintenanceItemExecuteStatus;
import com.sugon.modules.device.consts.DevMaintenanceTicketStatus;
import com.sugon.modules.device.model.vo.DevMaintenanceTicketItemDetailVO;
import com.sugon.modules.device.model.vo.DevMaintenanceTicketVO;
import com.sugon.modules.device.model.vo.DevTemMaintenanceTicketParamVO;
import com.sugon.modules.device.model.vo.DevTemPmTicketAdjustParam;
import com.sugon.service.DevMaintenanceTicketItemService;
import com.sugon.service.DevMaintenanceTicketService;
import com.sugon.utils.Constant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 设备维护工单数据Service实现类
 *
 * @author YuXD
 * @date 2020-11-15 15:08
 */
@Service("devMaintenanceTicketService")
public class DevMaintenanceTicketServiceImpl implements DevMaintenanceTicketService {

    @Resource
    private DevMaintenanceTicketDao devMaintenanceTicketDao;
    @Resource
    private DevMaintenanceTicketItemDao devPmItemDao;
    @Resource
    private DevMaintenanceTicketItemService maintenanceTicketItemService;

    @Override
    public int countUnCompleteTicketNum(SysUserEntity loginUser) {
        Map<String, Object> params = MapUtil.newHashMap();
        // 查看本月的工单
        DateTime current = DateUtil.date();
        params.put("startTime", DateUtil.formatDateTime(DateUtil.beginOfMonth(current)));
         /*
                默认显示当月维护工单， 如果月末这一天所在的周末跨月了。
                那么需要将统计的截止时间推迟到周末
             */
        Date endTime = DateUtil.endOfMonth(current);
        Date endOfWeek = DateUtil.endOfWeek(endTime);
        if (DateUtil.month(endTime) + 1 == DateUtil.month(endOfWeek)) {
            endTime = endOfWeek;
        }
        params.put("endTime", DateUtil.formatDateTime(endTime));

        /*
            维修组长可以看到车间下所有的维护工单执行情况
            维修工只看分配给自己的
         */
        if (loginUser.getLeader() != 1) {
            params.put("executor", loginUser.getUserId());
        } else {
            params.put("deptCode", loginUser.getDeptCode());
        }
        // 除了完成、延期完成、终止的，都给他显示
        params.put("statusList", CollectionUtil.newArrayList(DevMaintenanceTicketStatus.DISPATCHING, DevMaintenanceTicketStatus.WAIT_EXECUTE, DevMaintenanceTicketStatus.MAINTAINING, DevMaintenanceTicketStatus.DELAY_APPLYING, DevMaintenanceTicketStatus.DELAY_MAINTAINING, DevMaintenanceTicketStatus.OVERTIME));
        return queryAllTotal(params);
    }

    @Override
    public DevMaintenanceTicketEntity queryObjectByRepairCode(String repairCode) {
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("repairCode", repairCode);
        List<DevMaintenanceTicketEntity> pmTicketList = queryList(params);
        return CollectionUtil.isNotEmpty(pmTicketList) ? pmTicketList.get(0) : null;
    }

    /**
     * queryObject
     *
     * @param id 主键
     * @return
     */
    @Override
    public DevMaintenanceTicketEntity queryObject(String id) {
        return devMaintenanceTicketDao.queryObject(id);
    }

    /**
     * queryAll
     *
     * @param map 参数
     * @return
     */
    @Override
    public List<DevMaintenanceTicketVO> queryAll(Map<String, Object> map) {
        return devMaintenanceTicketDao.queryAll(map);
    }

    /**
     * queryAllTotal
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryAllTotal(Map<String, Object> map) {
        return devMaintenanceTicketDao.queryAllTotal(map);
    }


    @Override
    public List<DevMaintenanceTicketVO> queryAllForMobile(Map<String, Object> map) {
        return devMaintenanceTicketDao.queryAllForMobile(map);
    }

    @Override
    public int queryAllTotalForMobile(Map<String, Object> map) {
        return devMaintenanceTicketDao.queryAllTotalForMobile(map);
    }

    /**
     * queryList
     *
     * @param map 参数
     * @return
     */
    @Override
    public List<DevMaintenanceTicketEntity> queryList(Map<String, Object> map) {
        return devMaintenanceTicketDao.queryList(map);
    }

    @Override
    public List<DevMaintenanceTicketEntity> queryListByDevId(String devId) {
        DevMaintenanceTicketEntity param = new DevMaintenanceTicketEntity();
        param.setDevId(devId);
        return queryList(BeanUtil.beanToMap(param));
    }

    /**
     * queryTotal
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return devMaintenanceTicketDao.queryTotal(map);
    }

    /**
     * save
     *
     * @param devMaintenanceTicket 实体
     * @return
     */
    @Override
    public int save(DevMaintenanceTicketEntity devMaintenanceTicket) {
        devMaintenanceTicket.setId(RandomUtil.randomString(32));
        devMaintenanceTicket.setGmtCreate(DateUtil.date());
        devMaintenanceTicket.setDelFlag(Constant.IS_NOT_DEL_INT);
        devMaintenanceTicket.setIsUrged(0);
        devMaintenanceTicket.setRepairCode(generateUniqueCode());
        devMaintenanceTicket.setFinalEndTime(devMaintenanceTicket.getEndTime());
        return devMaintenanceTicketDao.save(devMaintenanceTicket);
    }

    @Override
    public String generateUniqueCode(Object object) {
        DevMaintenanceTicketEntity pmTicket = (DevMaintenanceTicketEntity) object;
        String current = DateUtil.format(pmTicket.getStartTime(), DatePattern.PURE_DATE_PATTERN);
        // 构建工单编码前缀
        String ticketCodePrefix = ErmsCodePrefix.MAINTENANCE_TICKET_CODE_PREFIX + current + "-";
        // 获取已上述前缀开头的最新工单编码
        String lastestMaintenanceCode = devMaintenanceTicketDao.getLastestMaintenanceCode(ticketCodePrefix);
        return com.sugon.modules.utils.StrUtil.increase(lastestMaintenanceCode, ticketCodePrefix, 4, 1);
    }

    /**
     * generateUniqueCode
     *
     * @return
     */
    @Override
    public String generateUniqueCode() {
        // 构建工单编码前缀
        String ticketCodePrefix = ErmsCodePrefix.MAINTENANCE_TICKET_CODE_PREFIX + com.sugon.modules.utils.DateUtil.today() + "-";
        // 获取已上述前缀开头的最新工单编码
        String lastestMaintenanceCode = devMaintenanceTicketDao.getLastestMaintenanceCode(ticketCodePrefix);
        return com.sugon.modules.utils.StrUtil.increase(lastestMaintenanceCode, ticketCodePrefix, 4, 1);
    }

    /**
     * update
     *
     * @param devMaintenanceTicket 实体
     * @return
     */
    @Override
    public int update(DevMaintenanceTicketEntity devMaintenanceTicket) {
        return devMaintenanceTicketDao.update(devMaintenanceTicket);
    }

    /**
     * delete
     *
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        // 先删除维护工单项
        devPmItemDao.deleteByTicketId(id);
        // 再删除维护工单
        return devMaintenanceTicketDao.delete(id);
    }

    /**
     * deleteBatch
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(String[] ids) {
        return devMaintenanceTicketDao.deleteBatch(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DevMaintenanceTicketEntity addTemporaryPlan(DevTemMaintenanceTicketParamVO temPlanParam) {
        /*
            1、保存临时维护计划
            2、保存临时维护计划明细
            3、给对应车间的生产班组长发送企业微信消息
         */
        // 创建维护工单基础信息
        DevMaintenanceTicketEntity pmTicket = new DevMaintenanceTicketEntity();
        pmTicket.setDevId(temPlanParam.getDevId());
        pmTicket.setWorkshop(temPlanParam.getWorkshopId());
        pmTicket.setStartTime(DateUtil.beginOfDay(temPlanParam.getStartDate()));
        pmTicket.setEndTime(DateUtil.endOfDay(temPlanParam.getEndDate()));
        pmTicket.setStatus(DevMaintenanceTicketStatus.DISPATCHING);
        pmTicket.setTicketType(temPlanParam.getTicketType().name());
        pmTicket.setWeekOfYear(DateUtil.weekOfYear(temPlanParam.getStartDate()));
        pmTicket.setYearly(DateUtil.year(pmTicket.getStartTime()));
        // 1、保存临时维护计划
        if (save(pmTicket) > 0) {
            // 2、保存临时维护计划明细
            DevMaintenanceTicketItemEntity devMaintenanceTicketItem = new DevMaintenanceTicketItemEntity();
            devMaintenanceTicketItem.setProblemDesc(temPlanParam.getDesc());
            devMaintenanceTicketItem.setStep(temPlanParam.getStep());
            devMaintenanceTicketItem.setDevMainTicketId(pmTicket.getId());
            devMaintenanceTicketItem.setStatus(DevMaintenanceItemExecuteStatus.UN);
            // 默认无异常，实际实施过程中可修改
            devMaintenanceTicketItem.setCheckResult(0);
            maintenanceTicketItemService.save(devMaintenanceTicketItem);
        }
        return pmTicket;
    }

    @Override
    public DevMaintenanceTicketEntity adjustTemporaryPlan(DevTemPmTicketAdjustParam temPlanParam) {
        DevMaintenanceTicketEntity matchedPmTicket = queryObject(temPlanParam.getPmTicketId());
        Assert.notNull(matchedPmTicket);
        matchedPmTicket.setStartTime(DateUtil.beginOfDay(temPlanParam.getStartDate()));
        matchedPmTicket.setEndTime(DateUtil.endOfDay(temPlanParam.getEndDate()));
        matchedPmTicket.setFinalEndTime(matchedPmTicket.getEndTime());
        matchedPmTicket.setWeekOfYear(DateUtil.weekOfYear(matchedPmTicket.getStartTime()));
        matchedPmTicket.setYearly(DateUtil.year(matchedPmTicket.getStartTime()));
        if (update(matchedPmTicket) > 0) {
            List<DevMaintenanceTicketItemDetailVO> pmItemList = maintenanceTicketItemService.queryByTicketId(temPlanParam.getPmTicketId());
            if (CollectionUtil.isNotEmpty(pmItemList)) {
                for (DevMaintenanceTicketItemDetailVO pmItem : pmItemList) {
                    pmItem.setProblemDesc(temPlanParam.getDesc());
                    pmItem.setStep(temPlanParam.getStep());
                    maintenanceTicketItemService.update(pmItem);
                }
            } else {
                // 2、保存临时维护计划明细
                DevMaintenanceTicketItemEntity devMaintenanceTicketItem = new DevMaintenanceTicketItemEntity();
                devMaintenanceTicketItem.setProblemDesc(temPlanParam.getDesc());
                devMaintenanceTicketItem.setStep(temPlanParam.getStep());
                devMaintenanceTicketItem.setDevMainTicketId(matchedPmTicket.getId());
                devMaintenanceTicketItem.setStatus(DevMaintenanceItemExecuteStatus.UN);
                // 默认无异常，实际实施过程中可修改
                devMaintenanceTicketItem.setCheckResult(0);
                maintenanceTicketItemService.save(devMaintenanceTicketItem);
            }
        }
        return matchedPmTicket;
    }
}
